const config = require('../config')
const axios = require('axios')
import { Toast } from 'vant'
import vue from 'vue'

//网络错误码
function err(code) {
    switch (code) {
        case 200:
            return true;
        case 400:
            Toast.fail('错误请求')
            break;
        case 401:
            Toast.fail('未授权,请重新登录')
            break;
        case 403:
            Toast.fail('拒绝访问')
            break;
        case 404:
            Toast.fail('请求错误,未找到该资源')
            break;
        case 405:
            Toast.fail('请求方法未允许')
            break;
        case 408:
            Toast.fail('请求超时')
            break;
        case 500:
            Toast.fail('服务器出错')
            break;
        case 501:
            Toast.fail('网络未实现')
            break;
        case 502:
            Toast.fail('网络出错')
            break;
        case 503:
            Toast.fail('服务不可用')
            break;
        case 504:
            Toast.fail('网络超时')
            break;
        case 505:
            Toast.fail('http版本不支持该请求')
            break;
    }
    return
}

//拼接版本和检查是否传了必传参数
function getv(url, data, method) {
    //获取全部接口数据
    var init = JSON.parse(window.localStorage.getItem(config.get('v')+'_init'))
    /*取链接*/
    var s=[];                                         //可能
    for(var i=0;i<init.length;i++){
        if(init[i].action==url){
            if(init[i].edition.substring(0,1)=='v'){
                var num=init[i].edition.substring(1,5)  //接口版本号
                var v=config.get('v').substring(1,5);   //客户端版本号
                if(num-v<=0){
                    init[i]['s']=v-num
                    s.push(init[i]);
                }
            }else{
                init[i]['s']=100000
                s.push(init[i]);
            }
        }
    }
    if(s.length==0){
        console.log('无接口');
        return ;
    }
    var mix=100000;
    var h=0;
    for (let i = 0; i < s.length; i++) {
        if(mix-s[i]['s']>0){
            mix=s[i]['s']
            h=i
        }
    }
    url = s[h].edition+'_'+s[h].action
    /*取链接*/
    //请求接口的所有版本
    var reqinit = []
    for (const i in init) {
        if (init[i].action != '' && url.includes(init[i].action)) {
            reqinit.push(init[i])
        }
    }
    //版本去除v后的数据
    var editionlist = []
    reqinit.forEach(item => {
        editionlist.push(item.edition.substring(1, item.edition.length))
    })
    // console.log(editionlist)

    //从大到小排序
    var ddx = editionlist.sort((a, b) => {
        return b - a;
    })
    //最新版本在所有请求接口版本的位置
    var endeditionindex = editionlist.findIndex(item => {
        return item == ddx[0]
    })
    //拼接
    //url = url + '_v' + ddx[0];
    // url =  'v' + ddx[0] +'_'+ url
    //默认能发送请求
    var canSend = true
    //默认不能发送请求的原因为空
    var noneData = []
    if (reqinit[endeditionindex].must && reqinit[endeditionindex].must != null) {
        if (reqinit[endeditionindex].must.includes('token') && method == 'get') {
            //需要传token的将token加到传递的参数中

            data.token = config.get('userInfo').token
        }
        if (reqinit[endeditionindex].must.includes('token') && method == 'post') {
            //需要传token的将token加到传递的参数中
            url = url + '?token=' + config.get('userInfo').token
        }
        //将必须的传参转为数组
        var must = reqinit[endeditionindex].must.split(',')
        for (const i in must) {
            if (must[i] == 'token') {
                must.splice(i, 1)
            }
        }
        //如果must不为空
        if (must != null) {
            must.forEach(item => {
                //如果用户传递的参数包含must 那么能发送请求
                if (data[item]) {
                    canSend = true
                } else {
                    //如果不包含 将信息加入到不能请求的原因中
                    noneData.push(item)
                    //不能发送请求
                    canSend = false
                }
            })
        }
    }
    return {url: url,cansend: canSend,noneData: noneData,data: data}
}

//get请求
export const get = function (url, data, callback) {
    var uurl = url
    var urin = getv(url, data, 'get')
    url = urin.url
    if (urin.cansend) {
        var xmlget = new XMLHttpRequest()
        //定义数组保存请求时传的参数
        var str = []
        for (let i in urin.data) {
            str.push(i + '=' + urin.data[i])
        }
        //将参数数组转为字符串并用& 拼接
        str = str.join('&')
        //拼接url
        if(config.get('userInfo').user.role_id==3){
            url = config.get('bpp_url') + url + '?' + str
        }else{
            url = config.get('app_url') + url + '?' + str
        }
        
        xmlget.open('get', url, true)
        //发送请求
        Toast.loading({
            message: '加载中...',
            forbidClick: true,
            loadingType: 'spinner',
        });
        xmlget.send()
        //获取加载动画节点
        var load = document.getElementById('loading')
        //显示加载动画
        load ? load.className = 'block' : ''
        xmlget.onreadystatechange = function () {
            //请求完成
            if (xmlget.readyState == 4) {
                //隐藏加载动画
                Toast.clear()
                load ? load.className = 'loadnone' : ''
                //请求返回的状态码
                err(xmlget.status)
                if (xmlget.status == 200) {
                    var resdata = JSON.parse(xmlget.responseText)
                    //服务器返回的状态码
                    switch (resdata.code) {
                        case 200:
                            break;
                        case 401:
                            axios.get(config.get('a_url') + '/checkoutLoginType?key=' + config.get('userInfo').key + '&sertype=1')
                                .then(res => {
                                    if (res.data.code == 200) {
                                        get('/index/index/login', { key: res.data.data.key }, res => {
                                            config.setUserInfo(res.data);
                                            get(uurl, data, res => {
                                                callback(res)
                                            })
                                        })
                                    } else {
                                        Toast.fail('登录信息失效,请重新登录')
                                        window.localStorage.clear()
                                        window.sessionStorage.clear()
                                        config.clear()
                                        vue.$router.push('/login')
                                    }
                                })
                            break;
                        case 499:
                            Toast.fail('未授权')
                            break
                        default:
                            //Toast.fail(resdata.data)
                            break;
                    }
                    callback(resdata)
                }else{
                    Toast.fail('发生错误');
                }
            }
        }
    } else {
        // Toast.fail('缺少参数' + urin.noneData)
    }
}

//post请求
export const post = function (url, data, callback) {
    var uurl = url
    var urin
    if (data.params) {
        urin = getv(url, data.params, 'post')
    } else {
        urin = getv(url, data, 'post')
    }
    if (urin.cansend) {
        var xmlpost = new XMLHttpRequest()
        if(config.get('userInfo').user.role_id==3){
            url = config.get('bpp_url') + urin.url
        }else{
            url = config.get('app_url') + urin.url
        }
        
        xmlpost.open('post', url, true)
        if (data.header) {
            for (let i in data.header) {
                xmlpost.setRequestHeader(i, data.header[i]);
            }
        }
        Toast.loading({
            message: '加载中...',
            forbidClick: true,
            loadingType: 'spinner',
        });
        xmlpost.send(urin.data)
        var load = document.getElementById('loading')

        load ? load.className = 'block' : ''
        xmlpost.onreadystatechange = function () {
            if (xmlpost.readyState == 4) {
                Toast.clear()
                load ? load.className = 'loadnone' : ''
                err(xmlpost.status)
                if (xmlpost.status == 200) {
                    var resdata = JSON.parse(xmlpost.responseText)
                    //服务器返回的状态码
                    switch (resdata.code) {
                        case 200:
                            break;
                        case 401:
                            axios.get(config.get('a_url') + '/checkoutLoginType?key=' + config.get('userInfo').key + '&sertype=1')
                                .then(res => {
                                    if (res.data.code == 200) {
                                        get('/index/index/login', { key: res.data.data.key }, res => {
                                            config.setUserInfo(res.data);
                                            post(uurl, data, res => {
                                                callback(res)
                                            })
                                        })
                                    } else {
                                        Toast.fail('登录信息失效,请重新登录')
                                        window.localStorage.clear()
                                        window.sessionStorage.clear()
                                        config.clear()
                                        vue.$router.push('/login')
                                    }
                                })
                            break;
                        case 499:
                            Toast.fail('未授权')
                            break;
                        default:
                            Toast.fail(resdata.data)
                            break;
                    }
                    callback(resdata)
                }else{
                    Toast.fail('发生错误');
                }
            }
        }
    } else {
        Toast.fail('缺少参数' + urin.noneData)
    }
}


